#!/usr/bin/env python3
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.utils import ImageReader
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import reportlab
import os
import textwrap
from datetime import datetime

summary_txt = '/home/ubantu00/zk_demo/build/results_summary_full.txt'
plots_dir = '/home/ubantu00/zk_demo/build/plots'
out_pdf = '/home/ubantu00/zk_demo/build/zk_report.pdf'

c = canvas.Canvas(out_pdf, pagesize=A4)
width, height = A4

# Register a Unicode TTF font (prefer DejaVuSans)
font_name = 'DejaVuSans'
font_bold = 'DejaVuSans-Bold'
font_path_candidates = [
    '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
    '/usr/local/share/fonts/DejaVuSans.ttf',
]
registered = False
for p in font_path_candidates:
    if os.path.exists(p):
        try:
            # register regular and bold aliases using same TTF (ReportLab will simulate weight)
            pdfmetrics.registerFont(TTFont(font_name, p))
            pdfmetrics.registerFont(TTFont(font_bold, p))
            registered = True
            break
        except Exception:
            registered = False
if not registered:
    # fallback to builtin Helvetica
    font_name = 'Helvetica'
    font_bold = 'Helvetica-Bold'

# Title page
c.setFont(font_bold if registered else font_name, 20)
c.drawCentredString(width/2, height-100, 'zk-SNARKs Benchmark Report')

c.setFont(font_name, 12)
c.drawCentredString(width/2, height-130, f'Generated: {datetime.now().isoformat(sep=" ", timespec="seconds")}')

# Add brief note
note = 'This report contains per-scenario statistics (mean, std, median, percentiles) and distribution plots (prove/verify histograms and boxplots).'
text = c.beginText(40, height-180)
text.setFont('Helvetica', 11)
for line in textwrap.wrap(note, 100):
    text.textLine(line)
c.drawText(text)
c.showPage()

# Read summary and split per scenario
with open(summary_txt) as f:
    content = f.read()

# We'll split by blank lines between scenarios
scenarios = [s.strip() for s in content.split('\n\n') if s.strip()]

for s in scenarios:
    # header lines
    lines = s.splitlines()
    title = lines[0] if lines else 'Scenario'

    c.setFont(font_bold if registered else font_name, 16)
    c.drawString(40, height-60, title)
    c.setFont(font_name, 10)
    y = height-90
    for ln in lines[1:]:
        for wrapped in textwrap.wrap(ln, 120):
            c.drawString(40, y, wrapped)
            y -= 14
            if y < 200:
                c.showPage()
                y = height-60
    # add plots for this scenario if exist
    # derive safe name
    scen_name = title.split(':',1)[0].strip()
    safe = scen_name.replace('/', '_').replace(' ', '_')
    # look for images that contain safe
    imgs = []
    for fname in sorted(os.listdir(plots_dir)):
        if safe in fname:
            imgs.append(os.path.join(plots_dir, fname))
    # place images, two per page
    for img in imgs:
        try:
            ir = ImageReader(img)
            iw, ih = ir.getSize()
            max_w = width - 80
            max_h = (height - 200)
            scale = min(max_w/iw, max_h/ih, 1.0)
            draw_w = iw * scale
            draw_h = ih * scale
            x = (width - draw_w)/2
            y_img = 120
            c.drawImage(ir, x, y_img, draw_w, draw_h)
            c.showPage()
        except Exception as e:
            # skip image on error
            continue

c.save()
print('Wrote', out_pdf)
